import { Form, Input, Button, Row, Col, message } from "antd";
import { getRate, updateRate } from "@/lib/request/api";
import { useEffect } from "react";

interface RateConfigProps {
  type: "enterprise" | "personal";
}

export default function RateConfig({ type }: RateConfigProps) {
  const [form] = Form.useForm();

  const fetchRate = async () => {
    try {
      const res = await getRate();
      return res;
    } catch (e: any) {
      message.error(
        e?.response?.data?.message || e?.response?.data || "failed"
      );
    }
  };

  // 获取费率数据并回显
  const fetchAndSetRate = async () => {
    const rateData = await fetchRate();
    
    // 根据类型选择不同的配置
    const r = type === "enterprise" 
      ? rateData.data.config 
      : rateData.data.individualConfig;

    console.log('config data:', r);

    if (rateData) {
      form.setFieldsValue({
        UTOCNY: { feeRate: r.UTOCNY?.feeRate },
        LEGALTOCNY: { feeRate: r.LEGALTOCNY?.feeRate },
        UTOLEGAL: { feeRate: r.UTOLEGAL?.feeRate },
        LEGALTOU: {
          feeRate: r.LEGALTOU?.feeRate,
          addConfig: {
            USD: r.LEGALTOU?.addConfig?.USD,
            EUR: r.LEGALTOU?.addConfig?.EUR,
            CNH: r.LEGALTOU?.addConfig?.CNH,
          },
        },
        LEGALTOLEGAL: {
          feeRate: r.LEGALTOLEGAL?.feeRate,
          minConfig: {
            USD: r.LEGALTOLEGAL?.minConfig?.USD,
            EUR: r.LEGALTOLEGAL?.minConfig?.EUR,
            CNH: r.LEGALTOLEGAL?.minConfig?.CNH,
          },
        },
        UTOU: {
          addConfig: {
            USDC: r.UTOU?.addConfig?.USDC,
            USDT: r.UTOU?.addConfig?.USDT,
          },
        },
        ACCOUNT: {
          addConfig: {
            USDT: r.ACCOUNT?.addConfig?.USDT,
            USDC: r.ACCOUNT?.addConfig?.USDC,
            USD: r.ACCOUNT?.addConfig?.USD,
          },
        },
        MANAGEBYMONTH: {
          addConfig: {
            USDT: r.MANAGEBYMONTH?.addConfig?.USDT,
            USDC: r.MANAGEBYMONTH?.addConfig?.USDC,
            USD: r.MANAGEBYMONTH?.addConfig?.USD,
          },
        },
      });
    }
  };

  useEffect(() => {
    fetchAndSetRate();
  }, [type]);

  const onFinish = async (values: any) => {
    const Params = {
      tenantType: type === "enterprise" ? 1 : 2,
      feeConfig: {
        ...values,
        UTOU: {
          feeRate: 0,
          addConfig: {
            USDC: values.UTOU.addConfig?.USDC,
            USDT: values.UTOU.addConfig?.USDT,
          },
        },
      },
    };
    try {
      const r = await updateRate(Params);
      if (r.code === 200) {
        message.success("配置成功");
        fetchAndSetRate();
      }
    } catch (e: any) {
      message.error(
        e?.response?.data?.message || e?.response?.data || "failed"
      );
    }
  };

  const validateAmount = (_rule: any, value: string, callback: any) => {
    if (!/^\d+(\.\d{1,2})?$/.test(value)) {
      callback("请输入数字，最多保留两位小数");
      return;
    }
    const floatValue = parseFloat(value);
    if (floatValue < 0) {
      callback("金额不能为负数");
    } else {
      callback();
    }
  };

  const validateAmounts = (_rule: any, value: string, callback: any) => {
    if (!/^\d+(\.\d{1,6})?$/.test(value)) {
      callback("请输入数字，最多保留两位小数");
      return;
    }
    const floatValue = parseFloat(value);
    if (floatValue < 0) {
      callback("金额不能为负数");
    } else {
      callback();
    }
  };

  return (
    <div>
      <Form
        form={form}
        layout="horizontal"
        onFinish={onFinish}
        wrapperCol={{ span: 30 }}
        labelCol={{ span: 6 }}
      >
        <Form.Item label="开户费">
          <Row gutter={8}>
            <Col span={4}>
              <Form.Item
                name={["ACCOUNT", "addConfig", "USDT"]}
                rules={[{ validator: validateAmount }]}
              >
                <Input placeholder="请输入" addonAfter="USDT" />
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item
                name={["ACCOUNT", "addConfig", "USDC"]}
                rules={[{ validator: validateAmount }]}
              >
                <Input placeholder="请输入" addonAfter="USDC" />
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item
                name={["ACCOUNT", "addConfig", "USD"]}
                rules={[{ validator: validateAmount }]}
              >
                <Input placeholder="请输入" addonAfter="USD" />
              </Form.Item>
            </Col>
          </Row>
        </Form.Item>

        <Form.Item label="账户管理费（月）" style={{ marginTop: "-25px" }}>
          <Row gutter={8}>
            <Col span={4}>
              <Form.Item
                name={["MANAGEBYMONTH", "addConfig", "USDT"]}
                rules={[{ validator: validateAmount }]}
              >
                <Input placeholder="请输入" addonAfter="USDT" />
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item
                name={["MANAGEBYMONTH", "addConfig", "USDC"]}
                rules={[{ validator: validateAmount }]}
              >
                <Input placeholder="请输入" addonAfter="USDC" />
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item
                name={["MANAGEBYMONTH", "addConfig", "USD"]}
                rules={[{ validator: validateAmount }]}
              >
                <Input placeholder="请输入" addonAfter="USD" />
              </Form.Item>
            </Col>
          </Row>
        </Form.Item>

        <Form.Item
          label="U到CNY"
          name={["UTOCNY", "feeRate"]}
          style={{ marginTop: "-25px" }}
          rules={[{ validator: validateAmount }]}
        >
          <Input placeholder="请输入" addonAfter="%" style={{ width: "30%" }} />
        </Form.Item>

        <Form.Item
          label="法到CNY"
          name={["LEGALTOCNY", "feeRate"]}
          rules={[{ validator: validateAmount }]}
        >
          <Input placeholder="请输入" addonAfter="%" style={{ width: "30%" }} />
        </Form.Item>

        <Form.Item
          label="U币USDT/USDC转法币USD/EUR/CNH"
          name={["UTOLEGAL", "feeRate"]}
          rules={[{ validator: validateAmount }]}
        >
          <Input placeholder="请输入" addonAfter="%" style={{ width: "30%" }} />
        </Form.Item>

        <Form.Item label="法币USD/EUR/CNH转U币USDT/USDC">
          <Row gutter={8}>
            <Col span={4}>
              <Form.Item
                name={["LEGALTOU", "feeRate"]}
                rules={[{ validator: validateAmount }]}
              >
                <Input placeholder="请输入" addonAfter="%" />
              </Form.Item>
            </Col>
            <Col span={1}>
              <div style={{ marginTop: "10px" }}>增加</div>
            </Col>

            <Col span={4}>
              <Form.Item
                name={["LEGALTOU", "addConfig", "USD"]}
                rules={[{ validator: validateAmount }]}
              >
                <Input placeholder="请输入" addonAfter="USD/笔" />
              </Form.Item>
            </Col>
            <Col span={1}>
              <div style={{ marginTop: "10px" }}>增加</div>
            </Col>

            <Col span={4}>
              <Form.Item
                name={["LEGALTOU", "addConfig", "EUR"]}
                rules={[{ validator: validateAmount }]}
              >
                <Input placeholder="请输入" addonAfter="EUR/笔" />
              </Form.Item>
            </Col>
            <Col span={1}>
              <div style={{ marginTop: "10px" }}>增加</div>
            </Col>

            <Col span={4}>
              <Form.Item
                name={["LEGALTOU", "addConfig", "CNH"]}
                rules={[{ validator: validateAmount }]}
              >
                <Input placeholder="请输入" addonAfter="CNH/笔" />
              </Form.Item>
            </Col>
          </Row>
        </Form.Item>

        <Form.Item
          label="法币USD/EUR/CNH跨行互转"
          style={{ marginTop: "-25px" }}
        >
          <Row gutter={8}>
            <Col span={4}>
              <Form.Item
                name={["LEGALTOLEGAL", "feeRate"]}
                rules={[{ validator: validateAmount }]}
              >
                <Input placeholder="请输入" addonAfter="%" />
              </Form.Item>
            </Col>
            <Col span={1}>
              <div style={{ marginTop: "10px" }}>最低</div>
            </Col>
            <Col span={4}>
              <Form.Item
                name={["LEGALTOLEGAL", "minConfig", "USD"]}
                rules={[{ validator: validateAmount }]}
              >
                <Input placeholder="请输入" addonAfter="USD/笔" />
              </Form.Item>
            </Col>
            <Col span={1}>
              <div style={{ marginTop: "10px" }}>最低</div>
            </Col>
            <Col span={4}>
              <Form.Item
                name={["LEGALTOLEGAL", "minConfig", "EUR"]}
                rules={[{ validator: validateAmount }]}
              >
                <Input placeholder="请输入" addonAfter="EUR/笔" />
              </Form.Item>
            </Col>
            <Col span={1}>
              <div style={{ marginTop: "10px" }}>最低</div>
            </Col>
            <Col span={4}>
              <Form.Item
                name={["LEGALTOLEGAL", "minConfig", "CNH"]}
                rules={[{ validator: validateAmount }]}
              >
                <Input placeholder="请输入" addonAfter="CNH/笔" />
              </Form.Item>
            </Col>
          </Row>
        </Form.Item>

        <Form.Item label="U币转U币" style={{ marginTop: "-25px" }}>
          <Row gutter={8}>
            <Col span={7.5}>
              <Form.Item
                name={["UTOU", "addConfig", "USDC"]}
                rules={[{ validator: validateAmounts }]}
              >
                <Input placeholder="请输入" addonAfter="USDC/笔" />
              </Form.Item>
            </Col>
            <Col span={7.5}>
              <Form.Item
                name={["UTOU", "addConfig", "USDT"]}
                rules={[{ validator: validateAmounts }]}
              >
                <Input placeholder="请输入" addonAfter="USDT/笔" />
              </Form.Item>
            </Col>
          </Row>
        </Form.Item>

        <Form.Item style={{ marginLeft: "40%" }}>
          <Button type="primary" htmlType="submit">
            确认
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}
